package fragments;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseFragment;
import com.example.administrator.newxlmedical.R;

import java.util.ArrayList;
import java.util.List;

import adapters.HospitalRegisterDepartAdapter;
import beans.AllDepts;
import beans.HospitalDepartBean;
import beans.HospitalRegisterDepartBean;
import beans.RegisterInfoBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import constants.Constants;
import constants.HandlerConstant;
import interfaces.MyItemClickListener;
import netframe.GetRetrofit;
import netframe.MyAction1;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;
import utils.ObjectSaveUtil;
import utils.ScreenUtils;
import utils.ToastUtil;

/**
 * Created by Administrator on 2018/5/16.
 */

public class TerminalInfoFragment extends BaseFragment {
    @BindView(R.id.et_info_terminal_name)
    EditText etName;
    @BindView(R.id.et_info_terminal_address)
    EditText etAddress;
    @BindView(R.id.et_info_terminal_departments)
    EditText etDepartments;
    @BindView(R.id.et_info_terminal_remark)
    EditText etRemark;
    Unbinder unbinder;
    @BindView(R.id.tv_info_terminal)
    TextView tvTerminal;
    @BindView(R.id.iv_terminal_search)
    ImageView ivSearch;
    @BindView(R.id.rv_terminal_info_dept)
    RecyclerView recyclerView;
    private TerminalInfoInterface infoInterface;
    private String departmentCode;
    private List<HospitalRegisterDepartBean> list = new ArrayList<>();
    private int count;
    private RegisterInfoBean bean;
    private HospitalRegisterDepartAdapter adapter;
    private String deptCode;
    private boolean isSearch = true;
    private boolean isCheckDept = false;

    private List<AllDepts> allDepts = new ArrayList<>();

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof TerminalInfoInterface) {
            infoInterface = (TerminalInfoInterface) activity;
        } else {
            throw new IllegalArgumentException("activity must implements TerminalInfoInterface");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_info_terminal, null);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initView() {
        super.initView();

        List<AllDepts> result = (List<AllDepts>) ObjectSaveUtil.readObject(mContext, Constants.ALL_DEPT, Constants.ALL_DEPT);
        if (result != null && result.size() != 0) {
            Log.e(TAG, "initView: result");
            allDepts.addAll(result);
        }

        adapter = new HospitalRegisterDepartAdapter(mContext, list);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        etDepartments.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (isSearch) {
                    if (!TextUtils.isEmpty(s.toString())) {
                        String text = s.toString();
                        list.clear();
                        if (Constants.IS_FUYI) {
                            getDepartment(text, 1);
                        } else {
                            getDepts(text);   //协和医院
                        }
                    } else {
                        recyclerView.setVisibility(View.GONE);
                    }
                } else {
                    isSearch = true;
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /*
        协和医院
     */
    private void getDepts(String text) {
        Log.e(TAG, "getDepts: " + allDepts.size());
        if (allDepts.size() != 0) {
            for (int i = 0; i < allDepts.size(); i++) {
                AllDepts allDepts = this.allDepts.get(i);
                String dept = allDepts.getKsmc();
                String code = allDepts.getKsdm();
                if (dept.contains(text)) {
                    HospitalRegisterDepartBean bean = new HospitalRegisterDepartBean();
                    bean.setDepartment(dept);
                    bean.setDeptCode(code);
                    list.add(bean);
                    Log.e(TAG, "list: " + dept);
                }
            }
            adapter.notifyDataSetChanged();
            recyclerView.setVisibility(View.VISIBLE);
        } else {
            ToastUtil.showToast(mContext, "没有缓存的科室!!!");
        }
    }

    @Override
    protected void setListener() {
        super.setListener();
        adapter.setItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                isCheckDept = true;
                String department = list.get(position).getDepartment();
                deptCode = list.get(position).getDeptCode();
                isSearch = false;
                etDepartments.setText(department);
                recyclerView.setVisibility(View.GONE);
                etDepartments.setSelection(department.length());
                list.clear();
                ScreenUtils.closeKeybord(etDepartments, mContext);
            }
        });
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @OnClick({R.id.tv_info_terminal, R.id.iv_terminal_search})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tv_info_terminal) {
            if (TextUtils.isEmpty(editToString(etName)) || TextUtils.isEmpty(editToString(etDepartments))) {
                ToastUtil.showToast(mContext, "医院名称和科室必须填写!");
            } else {
                if (isCheckDept || checkDept()) {
                    infoInterface.activate(editToString(etName), editToString(etAddress), editToString(etDepartments), editToString(etRemark), deptCode);
                } else {
                    ToastUtil.showToast(mContext, "请输入正确的科室!");
                }
            }
        } else if (view.getId() == R.id.iv_terminal_search) {
//            if (!TextUtils.isEmpty(etDepartments.getText().toString())) {
//                list.clear();
//                getDepartment(etDepartments.getText().toString().trim(), 1);
//            } else {
//                ToastUtil.showToast(mContext, "请输入科室");
//            }
        }
    }

    private boolean checkDept() {
        for (int i = 0; i < list.size(); i++) {
            HospitalRegisterDepartBean hospitalRegisterDepartBean = list.get(i);
            Log.e(TAG, hospitalRegisterDepartBean.getDepartment() + "   " + etDepartments.getText().toString());
            if (hospitalRegisterDepartBean.getDepartment().equals(etDepartments.getText().toString())) {
                return true;
            }
        }
        return false;
    }

    //1代表按搜索按钮,进行模糊查询,2是点击注册时,保证科室正确
    private void getDepartment(final String office, final int type) {
        GetRetrofit.getInstance2().getHospitalDepartment(office).subscribeOn(Schedulers.io()).groupBy(new Func1<List<HospitalDepartBean>, Boolean>() {
            @Override
            public Boolean call(List<HospitalDepartBean> hospitalDepartBeen) {
                return hospitalDepartBeen == null ? false : hospitalDepartBeen.size() > 0;

            }
        }).observeOn(AndroidSchedulers.mainThread()).flatMap(new Func1<GroupedObservable<Boolean, List<HospitalDepartBean>>, Observable<HospitalDepartBean>>() {
            @Override
            public Observable<HospitalDepartBean> call(GroupedObservable<Boolean, List<HospitalDepartBean>> booleanListGroupedObservable) {
                if (booleanListGroupedObservable.getKey()) {
                    return booleanListGroupedObservable.subscribeOn(Schedulers.io()).flatMap(new Func1<List<HospitalDepartBean>, Observable<HospitalDepartBean>>() {
                        @Override
                        public Observable<HospitalDepartBean> call(List<HospitalDepartBean> hospitalDepartBeen) {
                            return Observable.from(hospitalDepartBeen).doOnNext(new Action1<HospitalDepartBean>() {
                                @Override
                                public void call(HospitalDepartBean hospitalDepartBean) {
                                    if (type == 1) {
                                        HospitalRegisterDepartBean bean = new HospitalRegisterDepartBean();
                                        bean.setDepartment(hospitalDepartBean.get_dept_name());
                                        bean.setDeptCode(hospitalDepartBean.get_dept_code());
                                        list.add(bean);
                                    }
                                }
                            }).last().observeOn(AndroidSchedulers.mainThread());
                        }
                    });
                } else {
                    ToastUtil.showToast(mContext, "您输入的科室有误");
                    return null;
                }
            }
        }).subscribe(new Action1<HospitalDepartBean>() {
            @Override
            public void call(HospitalDepartBean hospitalDepartBean) {
                if (type == 1) {
                    recyclerView.setVisibility(View.VISIBLE);
                    adapter.notifyDataSetChanged();
                } else {
                    bean.setDepartment(hospitalDepartBean.get_dept_name());
                }
            }
        }, new MyAction1());
    }

    public interface TerminalInfoInterface {

        void activate(String name, String address, String departments, String remark, String deptCode);
    }

    private String editToString(EditText editText) {
        return editText.getText().toString().trim();
    }
}
